package common.utils
{

	import common.dataObjects.TreeVO;

	import mx.collections.ArrayCollection;
	import mx.controls.Alert;

	public class XMLUtil
	{
		public static function getNodeByValue(mainXML:XML, attributeName:String, attributeValue:String):XML
		{
			var result:XML = null;
			var children:XMLList = mainXML.children();
			for(var i:int=0; i < children.length(); i++)
			{
				var childrenXML:XML = children[i] as XML;

				var nodeAttributeValue:String = childrenXML.attribute(attributeName);
				if (StringUtil.isBlank(attributeValue) && StringUtil.isBlank(nodeAttributeValue) ) {
					result = childrenXML;
					break;
				} else  if ( childrenXML.attribute(attributeName) == attributeValue )  {
					result = childrenXML;
					break;
				}
			}
			if (result == null ) {
				result = mainXML;
			}
			return result;
		}

		public static function deleteNode(mainXML:XML, selectedNode:XML, attributeName:String):void
		{
			var children:XMLList = XMLList(selectedNode.parent()).children();
			for(var i:int=0; i < children.length(); i++)
			{
				if( XML(children[i]).attribute(attributeName) == selectedNode.attribute(attributeName) )
				{
					delete children[i];
				}
			}
		}

		private static function addChildrenNode(treeXML:XML,dataList:ArrayCollection,parentValue:String,currentNode:XML):void {
			for(var i:int=0; i<dataList.length; i++) {
				var treeVo : TreeVO = TreeVO(dataList.getItemAt(i));
				if (treeVo.nodeParentValue == parentValue ) {
					var x:XML = <iemsTree value="" label="" parentValue=""/>;
					x.@value = treeVo.nodeValue;
					x.@label = treeVo.nodeLabel;
					x.@parentValue = treeVo.nodeParentValue;
					//var parent:XML = XMLUtil.getNodeByValue(treeXML, "value", parentValue);
					//parent.appendChild(x);
					currentNode.appendChild(x);
					addChildrenNode(treeXML,dataList,treeVo.nodeValue,x);
					//break;
				}
			}
		}

		/**
		 * dataList 必须是TreeVo对象的list
		 */
		public static function generateTreeXML(dataList:ArrayCollection,rootParentValue:String,rootNodeXML:XML):XML {
			for(var i:int=0; i<dataList.length; i++) {
				var treeVo : TreeVO = TreeVO(dataList.getItemAt(i));
				//先增加根节点
				if (StringUtil.isEquals(rootParentValue , treeVo.nodeParentValue ) ) {
					var treeXML:XML = <iemsTree value="" label="" parentValue="">
								</iemsTree>;
					treeXML.@value = treeVo.nodeValue;
					treeXML.@label = treeVo.nodeLabel;
					treeXML.@parentValue = treeVo.nodeParentValue;
					if (rootNodeXML == null) {
						rootNodeXML = treeXML;
					} else {
						rootNodeXML.appendChild(treeXML);
					}
					addChildrenNode(rootNodeXML,dataList,treeVo.nodeValue,treeXML);
					//break;
				}
			}
			return rootNodeXML;
		}
	}
}